from itsdangerous import TimedJSONWebSignatureSerializer as itsdangerous
from apps.users.models import User
from meiduo_mall import settings


def generate_email(user):
    access_token = itsdangerous(settings.SECRET_KEY, expires_in=3600)
    data = {'user_id': user.id, 'email': user.email}
    token = access_token.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def check_email_token(token):
    access_token = itsdangerous(settings.SECRET_KEY, expires_in=3600)

    try:
        data = access_token.loads(token)

    except:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')

        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user
